package com.example.demo2.controller;

import com.example.demo2.entity.*;
import com.example.demo2.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@CrossOrigin
public class StudyController {

    // 获取当前工作目录的File对象
    File userDir = new File(System.getProperty("user.dir"));

    // 获取父目录的File对象，即D:/idea/
    File parentDir = userDir.getParentFile();

    // 再次获取上一级目录的File对象，即D:/
    File grandParentDir = parentDir.getParentFile();

    // 现在grandParentDir指向D:/，我们想在D:/下创建file目录
    // 因此，我们创建一个新的File对象指向D:/file
    File fileDir = new File(grandParentDir, "file");

    // 将fileDir转换为绝对路径
    String ROOT_PATH = fileDir.getAbsolutePath();

    private String UPLOAD_DIR = "uploads/";

    @Autowired
    private PmcMapper pmcMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private StandardMapper standardMapper;
    @Autowired
    private StudyMapper studyMapper;
    @Autowired
    private ProgramMapper programMapper;
    @Autowired
    private StudyDetailMapper studyDetailMapper;

    private ConcurrentHashMap<String, Integer> concurrentMap;

    @Autowired
    public void MyController(ConcurrentHashMap<String, Integer> concurrentMap) {
        this.concurrentMap = concurrentMap;
    }

    //检测人员查看所有证书
    @GetMapping("/findPmcByUID")
    public List<PermissionConnection> findPmcByUID()
    {
        Integer uID = (Integer) concurrentMap.get("uID");
        List<PermissionConnection> permissionConnections = pmcMapper.findPmcByUID(uID);
        for(PermissionConnection permissionConnection:permissionConnections)
        {
            Integer pjId=permissionConnection.getPjId();
            Project project=projectMapper.findProjectByPjId(pjId);
            if(project!=null)
            {
                permissionConnection.setPjName(project.getPjName());
                Standard standard=standardMapper.findStandardByStaId(project.getStaId());
                permissionConnection.setStaName(standard.getStaName());
            }
        }
        return permissionConnections;
    }

    //证书数量
    @GetMapping("/findPmcNumByUID")
    public int findPmcNumByUID()
    {
        Integer uID = (Integer) concurrentMap.get("uID");
        List<PermissionConnection> permissionConnections = pmcMapper.findPmcByUID(uID);
        return permissionConnections.size();
    }

    //学习记录搜索
    @GetMapping("/searchStudy")
    public List<Study> searchStudy(@RequestParam(value = "info", required = false) String info,
                                   @RequestParam(value = "year", required = false) String year,
                                   @RequestParam(value = "month", required = false) String month,
                                   @RequestParam(value = "day", required = false) String day){
        System.out.println(year);
        Integer uID = (Integer) concurrentMap.get("uID");
        //根据标准名称/项目名称搜索标准、项目
        List<Project> retList = new ArrayList<>();
        List<Standard> retStandard = new ArrayList<>();
        List<Study> retStudy = new ArrayList<>();
        if(info!=null&& !info.equals(""))
        {
            String query = "%" + info + "%";
            retList = projectMapper.searchProject(query);
            retStandard = standardMapper.searchStandard(query);
            //标准转换为项目
            for (Standard standard : retStandard) {
                List<Project> projects = projectMapper.findAllProjectBysatId(standard.getStaId());
                for (Project project : projects) {
                    if(!retList.contains(project)){
                        retList.add(project);
                    }
                }
            }
            for(Project project:retList)
            {
                Study study = studyMapper.searchStudyByPjId(uID,project.getPjId());
                retStudy.add(study);
            }
        }
        if(year!=null&& !year.equals(""))
        {
            String query = "%" + year;
            if(month!=null && !month.equals(""))
            {
                query = query +"-"+ month;
                if(day!=null && !day.equals(""))
                {
                    query = query +"-"+ day;
                }
                else {
                    query = query + "%";
                }
            }
            else {
                query = query + "%";
            }
            List<Study> studies = studyMapper.searchStudyByStartTime(query,uID);
            if(!studies.isEmpty())
            {
                if(!retStudy.isEmpty())
                {
                    for (Study study : studies) {
                        boolean exists = false;
                        for (Study study1 : retStudy) {
                            if(study1.getsId()==study.getsId()){
                                exists = true;
                                break;
                            }
                        }
                        if (!exists)
                        {
                            retStudy.add(study);
                        }
                    }
                }
                else {
                    retStudy = studies;
                }
            }
        }
        for(Study study:retStudy)
        {
            Integer pjId=study.getPjId();
            Project project=projectMapper.findProjectByPjId(pjId);
            if(project!=null)
            {
                study.setPjName(project.getPjName());
                Standard standard=standardMapper.findStandardByStaId(project.getStaId());
                study.setStaName(standard.getStaName());
            }
        }
        return retStudy;
    }

    //下载证书
    @GetMapping("/downloadPmc/{pmcId}")
    public String downloadPmc(@PathVariable int pmcId) {
        System.out.println("证书ID为："+pmcId);
        String pdfUrl = pmcMapper.findPmcUrlByPmcId(pmcId);
        if (pdfUrl == null) {
            return null;
        }
        return pdfUrl;
    }

    //获得检测人员所有学习记录
    @GetMapping("/findStudyByUID")
    public List<Study> findStudyByUID()
    {
        System.out.println("aaaaaaaaa");
        Integer uID = (Integer) concurrentMap.get("uID");
        List<Study> studies = studyMapper.findStudyByUID(uID);
        for(Study study:studies)
        {
            Integer pjId=study.getPjId();
            Project project=projectMapper.findProjectByPjId(pjId);
            if(project!=null)
            {
                study.setPjName(project.getPjName());
                Standard standard=standardMapper.findStandardByStaId(project.getStaId());
                study.setStaName(standard.getStaName());
            }
        }
        System.out.println(studies);
        return studies;
    }

    //培训界面
    @GetMapping("/findStudyByPjId/{pjId}")
    public Study findStudyByPjId(@PathVariable int pjId)
    {
        Integer uID = (Integer) concurrentMap.get("uID");
        if(uID==null)
            return null;
        Study study = new Study();
        study = studyMapper.findStudyByPjId(uID,pjId);

        //获取该项目下的所有视频id
        String pgType = "培训视频";
        List<Program> programs = programMapper.findProgramByPjId(pjId,pgType);

        if(study==null)
        {
            //未开始学习
            study = new Study();
            for(Program program:programs){
                study.setPerVideoStatus(program.getPgId(),false);
            }
            study.setsStatus(0);
            return study;
        }
        //初始化所有视频未观看
        else {
            for(Program program:programs){
                study.setPerVideoStatus(program.getPgId(),false);
            }
            int sId = study.getsId();
            //设置已观看视频
            List<StudyDetail> studyDetails = studyDetailMapper.findStudyDetailBySId(study.getsId());
            for (StudyDetail studyDetail : studyDetails) {
                study.setPerVideoStatus(studyDetail.getPgId(),true);
            }
        }
        return study;
    }

    //获得视频url
    @GetMapping("/getVideoUrl/{pgId}")
    public String getVideoUrl(@PathVariable int pgId){
        return programMapper.findPgUrlByPgId(pgId);
    }

    //点击观看视频
    @GetMapping("/watchVideo")
    public String watchVideo(@RequestParam(value = "sId", required = false) Integer sId,
                             @RequestParam(value = "pgId", required = false) Integer pgId)
    {
        StudyDetail studyDetail = studyDetailMapper.findStudyDetailByUId(sId,pgId);
        if(studyDetail==null)
        {
            //新增StudyDetail
            studyDetail = new StudyDetail();
            studyDetail.setSId(sId);
            studyDetail.setPgId(pgId);
            studyDetailMapper.insertStudyDetail(studyDetail);
        }
        return programMapper.findPgUrlByPgId(pgId);
    }

    //下载培训视频
    @GetMapping("/downloadVideo")
    public String downloadVideo(@RequestParam(value = "pjId", required = false) Integer pjId,
                                @RequestParam(value = "pgId", required = false) Integer pgId)  {
        System.out.println("aaaaaaaaaaaa"+pgId);
        Integer uID = (Integer) concurrentMap.get("uID");
        Study study = studyMapper.findStudyByPjId(uID,pjId);
        if(study==null)
        {
            System.out.println("bbbbbbbbbbb"+pgId);
            //未学习过,新增学习记录
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = dateFormat.format(now);
            study = new Study();
            study.setuID(uID);
            study.setPjId(pjId);
            study.setStartTime(startTime);
            studyMapper.insertStudy(study);
            study = studyMapper.findStudyByPjId(uID,pjId);

            //新增该视频的StudyDetail记录
            StudyDetail studyDetail = new StudyDetail();
            studyDetail.setSId(study.getsId());
            studyDetail.setPgId(pgId);
            studyDetailMapper.insertStudyDetail(studyDetail);

            //更新学习进度
            //获取该项目下的所有视频id
            String pgType = "培训视频";
            List<Program> programs = programMapper.findProgramByPjId(pjId,pgType);
            study.setsStatus((int) (1 /programs.size())*100);
            studyMapper.updateStatus(study.getsId(),study.getsStatus());
        }
        else {
            //是否学习过此视频
            System.out.println("aaaccccccccaaaaa"+pgId);
            StudyDetail studyDetail = studyDetailMapper.findStudyDetailByUId(study.getsId(),pgId);
            if(studyDetail==null)
            {
                System.out.println("ddddddddda"+pgId);
                //未学习过
                studyDetail = new StudyDetail();
                studyDetail.setSId(study.getsId());
                studyDetail.setPgId(pgId);
                studyDetailMapper.insertStudyDetail(studyDetail);
                //更新学习进度

                //获取该项目下的所有视频id
                String pgType = "培训视频";
                List<Program> programs = programMapper.findProgramByPjId(pjId,pgType);
                //获取所有已学习过的视频
                List<StudyDetail> studyDetail2 = studyDetailMapper.findStudyDetailBySId(study.getsId());
                study.setsStatus((int) (studyDetail2.size()/programs.size())*100);
                studyMapper.updateStatus(study.getsId(),study.getsStatus());
            }
        }
        //下载视频
        return programMapper.findPgUrlByPgId(pgId);


    }

    //获取试卷id
    @GetMapping("/findPaper/{pjId}")
    public int findPaper(@PathVariable int pjId)  {
        String pgType = "考核试卷";
        List<Program> programs = programMapper.findProgramByPjId(pjId,pgType);
        return programs.get(0).getPgId();
    }

    //下载试卷
    @GetMapping("/downloadPaper")
    public String downloadPaper(@RequestParam(value = "pgId", required = false) int pgId,
                                @RequestParam(value = "sId", required = false) int sId)  {
        String pgUrl = programMapper.findPgUrlByPgId(pgId);
        studyMapper.updatePaperStatus(sId);
        return pgUrl;
    }

    private ResponseEntity<String> uploadFile(MultipartFile file, String fileType,Integer sId) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件为空，请选择要上传的文件");
        }
        try {
            // 设置保存路径，确保文件保存在对外开放的目录
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            File destFile = new File(ROOT_PATH + File.separator  + fileType +File.separator + fileName);

            // 创建目录，如果不存在则创建
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }

            // 保存文件
            file.transferTo(destFile);

            // 生成完整的文件 URL
            String fileUrl = "http://localhost:8081/files/" + fileType + "/" + fileName;

            // 根据fileType来选择调用不同的Mapper方法
            if ("videos".equals(fileType)) {
                studyMapper.uploadVideoUrl(fileUrl,sId);
            } else if ("pdf".equals(fileType)) {
                studyMapper.uploadPaperUrl(fileUrl,sId);
            } else {
                return ResponseEntity.badRequest().body("不支持的文件类型");
            }
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = dateFormat.format(now);
            studyMapper.updateSTime(sId,startTime);

            return ResponseEntity.ok("文件上传成功：" + fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败: " + e.getMessage());
        }
    }

    //上传操作视频
    @PostMapping("/uploadVideo")
    public ResponseEntity<String> uploadVideo(@RequestParam("sId") Integer sId,
                                                      @RequestParam("file") MultipartFile file) {
        System.out.println(file.getOriginalFilename());
        return uploadFile(file, "videos", sId);
    }

    //上传pdf
    @PostMapping("/uploadPdf")
    public ResponseEntity<String> uploadPdf(@RequestParam("sId") Integer sId,
                                            @RequestParam("file") MultipartFile file) {
        return uploadFile(file, "pdf", sId);
    }


}
